/**
* ...
* @author Default
* @version 0.1
*/

package bdz.dms.vo{
	
	public class TemplateVO extends CoreDataVO {
		private var proplist:Array = ["tfield_id", "template_id", "type", "property_key"];
		private var propdelete:Array;
		
		function TemplateVO(xm:XML = null){	
			super(xm);
		}
		override protected function initialize():void {
			_properties = new Array();
			if(written){
				var counter:Number = 0;
				for each(var o:* in _localxml.properties.property){
					_properties[counter] = {};
					for each(var s:String in proplist){
						_properties[counter][s] = o[s];
					}
					counter++;
				}
				common_id = _localxml.template_id;
			}
		}
		public function get template_id():Number{
			return _localxml.template_id;
		}
		public function get template_name():String{
			return _localxml.template_name;
		}
		public function set template_name(str:String):void{
			_localxml.template_name = str;
		}
		public function updateProperty(id:Number, key:String, type:String):void{
			for each(var o:Object in _properties){
				if(o.tfield_id == id){
					o.property_key = key;
					o.type = type;
				}
			}
		}
		public function addProperty(key:String, type:String, tfid:Number = -1):void{
			var o:Object = {};
			o.tfield_id = tfid == -1 ? "temp_"+new Date().getTime() : tfid;
			o.property_key = key;
			o.type = type;
			o.template_id = _localxml.template_id;
			_properties.push(o);
		}
		public function removeProperty(pid:Number):void{
			if(propdelete == null){
				propdelete = new Array();
				_localxml.deleteprops = "";
			}
			for (var i:Number=0;i<_properties.length;i++){
				if(_properties[i].tfield_id == pid){
					deletePropIndex(i);
				}
			}
		}
		private function deletePropIndex(indx:Number):void{
			var xnode:XML = <todelete/>;
			xnode.tfield_id = _properties[indx].tfield_id;
			propdelete.push(xnode);
			_properties.splice(indx,1);
		}
		public function clone():TemplateVO{
			return new TemplateVO(_localxml);
		}
		override public function toXML():XML{
			var xvalue:XML = <dms/>;
			xvalue.template_id = _localxml.template_id;
			xvalue.template_name = _localxml.template_name;
			xvalue.properties = "";
			for (var i:Number = 0; i <_properties.length; i++) {
				var xnode:XML = <property/>
				for each(var s:String in proplist){
					if(s == "template_id"){
						xnode[s] = _localxml.template_id;	
					}else{
						if(s == "tfield_id"){
							try{
								if(_properties[i][s].indexOf("temp_") != -1){
									_properties[i][s] = null;
								}
							}catch(e:Error){
								
							}
						}
						if(_properties[i][s]){
							xnode[s] = _properties[i][s];
						}
					}
				}
				xvalue.properties.property[i] = xnode;
			}
			if(propdelete){
				xvalue.deleteprops = ""
				for each(var xx:XML in propdelete){
					xvalue.deleteprops.todelete[i] = xx;
				}
			}
			return xvalue;
		}
		
		
	}
	
}